package com.cloud.salon.gateway.component.filter;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cloud.salon.gateway.bean.AuthenticationBean;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.fasterxml.jackson.databind.ObjectMapper;

/*
 * @Description 自定义的登录请求信息获取拦截器
 * @Author wolf--LZH
 * @CreateDate 2019/4/16 0016 下午 2:35
 */
public class LoginAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
	
	@Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
		
		String contentType = request.getContentType();
		
        // 档请求数据为 JSON 时,获取验证信息
        if(MediaType.APPLICATION_JSON_UTF8_VALUE.equals(contentType)
        		|| MediaType.APPLICATION_JSON_VALUE.equals(contentType)){

            // 通过json工具映射json到验证类中
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authRequest = null;
            
            try (InputStream is = request.getInputStream()){
            	//读取JSON数据
                AuthenticationBean authenticationBean = mapper.readValue(is, AuthenticationBean.class);
                authRequest = new UsernamePasswordAuthenticationToken(
                        authenticationBean.getUsername(), authenticationBean.getPassword());
                
            }catch (IOException e) {
                authRequest = new UsernamePasswordAuthenticationToken("", "");
            }
            
            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        //transmit it to UsernamePasswordAuthenticationFilter
        else {
            return super.attemptAuthentication(request, response);
        }
    }
}
